package com.example.listener;

import com.example.lock.Lock;
import com.example.service.SysFinishJobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/***
 * 把已完成的任务归档到任务归档表，提升运行性能
 */
@Service
public class SysFinishJobTransferListener implements InitializingBean, DisposableBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private DataSource dataSource;

    @Resource
    private SysFinishJobService sysFinishJobService;

    private ScheduledExecutorService scheduledExecutorService;

    private String sql = "select * from sys_lock where id = 2 for update";

    @Override
    public void afterPropertiesSet() throws Exception {
        this.scheduledExecutorService = new ScheduledThreadPoolExecutor(2);
        this.scheduledExecutorService.scheduleAtFixedRate(new SysFinishJobTransferThread(), 0, 20, TimeUnit.SECONDS);
    }

    @Override
    public void destroy() throws Exception {
        this.scheduledExecutorService.shutdownNow();
    }

    /***
     * 任务转移的线程
     */
    class SysFinishJobTransferThread implements Runnable {

        @Override
        public void run() {
            Lock lock = null;
            try {
                lock = new Lock(dataSource, sql);
                lock.lock();
                sysFinishJobService.updateAndTransfer();
            } catch (Exception e) {
                logger.warn("job transfer error :" + e.getMessage());
            } finally {
                if (lock != null) {
                    lock.unlock();
                }
            }
        }
    }
}
